import { Button, Flex, Modal, Spin, Table } from 'antd';
import React, { useRef } from 'react';
import { useAntdTable } from 'ahooks';
import { deleteTaskById, getTaskList, startTaskById, stopTaskById, type DataItem } from './api';
import { columns } from './statics';
import UpdateDrawer from './updateDrawer';


const TaskManager: React.FC = () => {
  const { tableProps, loading, refresh } = useAntdTable(getTaskList);
  const $ref = useRef<any>(null);
  const handleCreate = () => {
    console.log('handleCreate');
    $ref.current.open();
  }

  const handleDelete = async (id: string) => {
    Modal.confirm({
      title: '确定删除',
      async onOk() {
        try {
          await deleteTaskById(id)
          refresh();
        } catch (error) {
          console.error(error);
        }
      },
    });
  }

  function handleEdit(data: DataItem) {
    $ref.current.open(data);
  }

  function handleEnable(row: DataItem) {
    Modal.confirm({
      title: '确定启用/禁用',
      async onOk() {
        try {
          if (row.enabled) {
            await stopTaskById(row.id);
          } else {
            await startTaskById(row.id);
          }
          refresh();
        } catch (error) {
          console.error(error);
        }
      },
    });
  }

  return (<>
    <Spin spinning={loading}>
      <Flex vertical gap={16}>
        <Flex gap={8}>
          <Button type="primary" onClick={handleCreate}>新增</Button>
        </Flex>
        <Table columns={columns({ handleDelete, handleEdit, handleEnable })} rowKey="id" style={{ overflow: 'auto' }} {...tableProps} />
      </Flex>
    </Spin>
    <UpdateDrawer onOk={refresh} ref={$ref}></UpdateDrawer>
  </>
  );
};

export default TaskManager;